
from cgitb import text
from copy import copy
from operator import truediv
from random import randint
from sqlite3 import Row
from textwrap import fill
from tkinter import *
import csv
import tkinter
import copy

from click import command


class GUI:

    # 相关初始化
    def __init__(self, maze) -> None:
        self.maze = maze
        self.backup = copy.deepcopy(self.maze)
        self.size = len(self.maze)

        self.pos = (0, 0)

        self.window = Tk()
        self.window.title('maze game')
        self.window.geometry('1000x1500')

        self.cv = Canvas(self.window, bg='white', width=1000, height=1500)

    # 渲染整个棋盘
    def renderMaze(self) -> None:
        for i in range(len(self.maze)):
            for j in range(len(self.maze[0])):
                if self.maze[i][j] == 0:     # road
                    bg = 'white'
                elif self.maze[i][j] == 1:   # wall
                    bg = 'gray'
                elif self.maze[i][j] == 2:   # agent
                    bg = 'blue'
                elif self.maze[i][j] == 3:   # end
                    bg = 'red'
                else:                        # diamond
                    bg = 'pink'
                id = self.cv.create_rectangle(
                    j*100, i*100, j*100 + 100, i*100+100, fill=bg)

        self.cv.pack()

    def reset(self) -> None:
        self.maze = copy.deepcopy(self.backup)
        self.pos = (0, 0)
        self.renderMaze()

    def mainloop(self) -> None:
        self.window.mainloop()

    def changeColor(self, pos, npos) -> None:
        # print('changeColor')
        # print('pos,next:', pos, npos)
        x, y = pos
        item = self.cv.find_closest(y * 100, x * 100)

        self.cv.itemconfigure(item, fill='white')

        nx, ny = npos
        item = self.cv.find_closest(ny * 100, nx * 100)
        self.cv.itemconfigure(item, fill='blue')

    def UP(self):
        x, y = self.pos
        item = self.cv.find_closest(x, y)
        self.cv.itemconfigure(item, fill="white")

        next_item = self.cv.find_closest(x, y-100)
        self.cv.itemconfigure(next_item, fill="blue")

        # 更新self.pos
        self.pos = x, y-100

    def DOWN(self):
        x, y = self.pos
        item = self.cv.find_closest(x, y)
        self.cv.itemconfigure(item, fill="white")

        next_item = self.cv.find_closest(x, y+100)
        self.cv.itemconfigure(next_item, fill="blue")

        self.pos = x, y+100

    def LEFT(self):
        x, y = self.pos
        item = self.cv.find_closest(x, y)
        self.cv.itemconfigure(item, fill="white")

        next_item = self.cv.find_closest(x-100, y)
        self.cv.itemconfigure(next_item, fill="blue")

        self.pos = x-100, y

    def RIGHT(self):
        x, y = self.pos
        item = self.cv.find_closest(x, y)
        self.cv.itemconfigure(item, fill="white")

        next_item = self.cv.find_closest(x+100, y)
        self.cv.itemconfigure(next_item, fill="blue")

        self.pos = x+100, y
